package com.itheima.job.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.job.OrderSettingJob;
import com.itheima.service.OrderSettingService;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/13 15:07
 */

/*@Lazy(false)
@Component
@EnableScheduling*/
public class CompleteScheduleConfig implements SchedulingConfigurer {

    @Reference
    private OrderSettingService orderSettingService;


    public static String cron = "0/5 * * * * ?";

    /**
     * 执行定时任务.
     */
    /*@Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //添加类
        OrderSettingJob orderSettingJob = new OrderSettingJob();
//        TestController testController = new TestController();
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () ->
//                        testController.method(),
                        orderSettingJob.settingOrder(),
                //2.设置执行周期(Trigger)
                (TriggerContext triggerContext) -> {
                    //2.1 从数据库获取执行周期
                    String cron = orderSettingService.getCron();
                    System.out.println(cron);
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }*/

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // 任务逻辑
                System.out.println("dynamicCronTask is running...");
                String cron = orderSettingService.getCron();

                if (cron != null && cron.length() > 0) {
                    CompleteScheduleConfig.cron = cron;
                }
                //添加类
                OrderSettingJob orderSettingJob = new OrderSettingJob();
                orderSettingJob.settingOrder();
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 任务触发，可修改任务的执行周期
                //2.1 从数据库获取执行周期
                CronTrigger trigger = new CronTrigger(cron);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });
    }
}


